package com.alkin.thing.framework.redis;

import cn.hutool.core.lang.Tuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

import java.nio.charset.StandardCharsets;
import java.util.function.Consumer;

/**
 * redis监听器
 *
 * @author huangzy
 */
public class MyRedisChannelListener implements MessageListener {
    private static final Logger log = LoggerFactory.getLogger(MyRedisChannelListener.class);
    /**
     * 监听处理器，Tuple分别携带address和body
     */
    private Consumer<Tuple> handler;

    public MyRedisChannelListener(Consumer<Tuple> handler) {
        this.handler = handler;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        byte[] channel = message.getChannel();
        byte[] body = message.getBody();
        String content = new String(body, StandardCharsets.UTF_8);
        String address = new String(channel, StandardCharsets.UTF_8);
        log.info("get " + content + " from " + address);
        this.handler.accept(new Tuple(address, content));
    }
}